package com.recharge.domain.context;

import com.recharge.common.util.RedisUtil;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.*;
import java.util.Collection;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 重写 shiro 权限框架的session dao 类
 *
 *  启用中
 */
@Component
public class SelfSessionDao extends AbstractSessionDAO {

    private static Logger logger = LoggerFactory.getLogger(SelfSessionDao.class);

    @Autowired
    private RedisUtil redisUtil;

    private final String prefix = "shiro:session:";


    // 创建session，保存到redis
    @Override
    protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        // 必须要将生成的id设置到session实力当中
        assignSessionId(session,sessionId);
        redisUtil.set(prefix + sessionId,session);
        return sessionId;
    }

    @Override
    protected Session doReadSession(Serializable sessionId) {
        return (Session) redisUtil.get(prefix + sessionId);
    }

    @Override
    public void update(Session session) throws UnknownSessionException {
        if (session == null || session.getId() == null) {
            throw new UnknownSessionException("session 或者 session为空");
        }
        redisUtil.set(prefix + session.getId(),session);
    }

    @Override
    public void delete(Session session) {
        redisUtil.del(prefix + session.getId());
    }

    @Override
    public Collection<Session> getActiveSessions() {
        Set<String> keys = redisUtil.keys(prefix + "*");

        if (keys != null) {
            return keys.stream().map(key -> {
                Session s = (Session) redisUtil.get(key);
                return s;
            }).collect(Collectors.toList());

        } else {
            return null;
        }
    }
}

